package com.wenwen.social.controller;

import com.wenwen.social.application.MessageApplication;
import com.wenwen.social.application.dto.MessageDTO;
import com.wenwen.social.application.dto.UserDTO;
import com.wenwen.social.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;

import static com.wenwen.social.constant.errorcode.CommonErrorConstant.*;

@RestController
public class MessageController extends BaseController {

	@Autowired
	private MessageApplication messageApplication;


	/**
	 * 创建信息
	 * test：http://localhost:8081/createMsg
	 * params:{"content":"first msg","type":2,"medias":{"mdatas":[{"url":"www.baidu.com","index":0},{"url":"www.baidu.com2","index":1}],"version":0}}
	 * @param msg  发送的消息
	 * @param type  消息类型  1.纯文本，2.图片，3.视频
	 * @param list  附件列表
	 * @return 消息id
	 */
	@PostMapping("/createMsg")
	public MessageDTO createMsg(@RequestBody MessageDTO dto) {
		checkParam(dto);

		UserDTO currLoginUser = getCurrLoginUser();
		checkUser(currLoginUser);

		Long id =  messageApplication.createMessage(currLoginUser.getId(),
				dto.getContent(),
				dto.getType(),
				dto.getMedias().getMdatas()
		);

		MessageDTO messageDTO = new MessageDTO();
		messageDTO.setId(id);
		return messageDTO;
	}

	private void checkUser(UserDTO currLoginUser) {
		if(currLoginUser == null) {
			throw new ServiceException(USER_NOT_LOGIN_CODE,USER_NOT_LOGIN_MSG);
		}
		if(currLoginUser.getId() == null){
			throw new ServiceException(USER_NOT_EXIST_CODE,USER_NOT_EXIST_MSG);
		}
	}

	private void checkParam(MessageDTO dto) {
		if(dto.getType().intValue() != 1 ){
			if(dto.getMedias() ==null ||
					dto.getMedias().getMdatas() == null ||
					dto.getMedias().getMdatas().isEmpty() ) {
				throw new ServiceException(PARAMETER_ILLGAL_CODE,"type:"+dto.getType().intValue()+"与传入列表数据不符合");
			}
		}
	}

	/**
	 * 删除特定消息
	 * test: http://localhost:8080/delMsg?msgId=1567698222817
	 * @param msgId
	 * @return 删除条数
	 */
	@PostMapping("/delMsg")
	public Integer delMsg(@NotNull(message = "没有选择消息") Long msgId) {
		UserDTO currLoginUser = getCurrLoginUser();
		if(currLoginUser == null) {
			throw new ServiceException(USER_NOT_LOGIN_CODE,USER_NOT_LOGIN_MSG);
		}
		if(currLoginUser.getId() == null){
			throw new ServiceException(USER_NOT_EXIST_CODE,USER_NOT_EXIST_MSG);
		}

		return messageApplication.delMessage(currLoginUser.getId(),msgId);
	}
}
